package com.mtq.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器 对没有登录的用户进行页面拦截
 * @author caowei
 *
 */
public class SessionFilter implements Filter{
	@SuppressWarnings("unused")
	private FilterConfig config;

	@Override
	public void destroy() {
		this.config = null;
	}

	/**
	 * 拦截器 分别对各种请求进行判断，如不符合则强制跳转到登录页面
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String uri = req.getRequestURI();
		if(uri.contains("/login") || uri.contains("login.jsp") 
				|| uri.equals(req.getContextPath()+"/")) {
			req.getSession().removeAttribute("user");
			chain.doFilter(req, res);
		} else if (uri.contains("/js") || uri.contains("/css")
				|| uri.contains("/images")){
			chain.doFilter(req, res);
		}else {
			Map<String,Object> user = (Map<String, Object>) req.getSession()
					.getAttribute("user");
			if(user == null) {
				String requestType = (String) ((HttpServletRequest) request)
						.getHeader("X-Requested-With");
				if (requestType != null && requestType.equals("XMLHttpRequest")) {
					PrintWriter pw = res.getWriter();
					pw.print("timeOut");
					pw.close();
				} else {
					req.getRequestDispatcher("/").forward(req, res);
				}
			}else {
				chain.doFilter(req, res);
			}
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
	}

}
